Tombloo.Service = {
	check : function(ctx){
		return withDocument(ctx.document, function(){
			return Tombloo.Service.extracters.check(ctx);
		});
	},
	
	alertError : function(ps, msg){
		error(msg);
		
		if(typeof(msg)!='string'){
			if(msg.name && msg.name.match('GenericError')){
				msg = msg.message;
			} else {
				msg = repr(msg);
			}
		}
		
		if(confirm([
			'Post failed.',
			msg.replace(/^/gm, '  '),
			'',
			'Will you reopen?',
			'Source page: ',
			'  ' + ps.page,
			'  ' + ps.pageUrl
		].join('\n'))){
			addTab(ps.pageUrl);
		}
	},
	
	share : function(ctx, ext, showForm){
		return succeed().addCallback(function(){
			return Tombloo.Service.extracters.extract(ctx, ext);
		}).addCallback(function(ps){
			log(ps);
			
			if(showForm){
				new QuickPostForm(ps).show();
				
				return succeed({});
			}
			
			var config = eval(getPref('postConfig'));
			return Tombloo.Service.post(ps, models.check(ps).filter(function(p){
				return config[p.name] && config[p.name][ps.type];
			}));
		}).addErrback(function(err){
			Tombloo.Service.alertError({
				page    : ctx.title,
				pageUrl : ctx.href,
			}, err);
		});
	},
	
	post : function(ps, posters){
		log(posters);
		
		var ds = {};
		posters = [].concat(posters);
		posters.forEach(function(p){
			ds[p.name] = p.post(ps);
		})
		
		return new DeferredHash(ds).addCallback(function(ress){
			log(ress);
			
			var errs = [];
			var ignoreError = getPref('ignoreError');
			ignoreError = ignoreError && new RegExp(getPref('ignoreError'), 'i');
			for(var name in ress){
				var [success, res] = ress[name];
				if(!success){
					var msg = '  ' + name + ': ' + 
						(res.message.status? 'HTTP Status Code '+res.message.status : res.message)
					if(!ignoreError || !msg.match(ignoreError))
						errs.push(msg);
				}
			}
			
			if(errs.length)
				throw errs.join('\n');
		});
	},
	
	update : function(user, type, p){
		p = p || new Progress();
		if(p.ended)
			return;
		
log('update : ---');
log('update : START');
log('update : user = ' + user);
log('update : type = ' + type);
	return succeed().
		addCallback(bind('getInfo', Tumblr), user, type).
		addCallback(function(info){
			p.max = info.total - Tombloo[type? capitalize(type) : 'Post'].countByUser(user);
log('update : ---');
log('update : p.max = ' + p.max);
log('update : p.ended = ' + p.ended);
			
			if(p.ended)
				return;
			
			return Tumblr.read(user, type, info.total, function(post){
// log('update : ---');
// log('update : UPDATE : ' + type);
// log('update : ' + p.value + '/' + p.max);
// log('update : p.ended = ' + p.ended);
				if(p.ended)
					throw StopProcess;
				
				try{
					Tombloo.Post.insert(post);
					p.value++;
				} catch(e if e instanceof Database.DuplicateKeyException) {
// log('update : DuplicateKeyException!!!!!!!!!!!!!!!!!!!!!!!!!!');
					// 重複エラーを無視し読み飛ばす
				}
			});
		}).
		addBoth(function(res){
log('update : ---');
log('update : END');
log('update : user = ' + user);
log('update : type = ' + type);
// log(res);
			}).
			addCallback(bind('complete', p));
	},
}


Tombloo.Service.Photo = {
	download : function(user, size, p){
		p = p || new Progress();
		if(p.ended)
			return;
log('download : ---');
log('download : user = ' + user);
log('download : size = ' + size);
	
	return Tombloo.Service.Photo.getByFileExists(user, size, false).
		addCallback(function(photos){
			p.max = photos.length;
log('download : ---');
log('download : p.max = ' + p.max);
			
			if(p.ended)
				return;
			
			return deferredForEach(photos, function(photo){
// log('download : ---');
// log('download : ' + p.value + '/' + p.max);
// log('download : ' + p.ended);
// log('download : ' + photo.getFile(size).leafName);
				if(p.ended)
					throw StopIteration;
				
				p.value++;
				
				return Tumblr.Photo.download(photo.getFile(size));
			});
		}).
		addBoth(function(res){
log('download : ---');
log('download : END');
// log(res);
			}).
			addBoth(bind('complete', p));
	},
	getByFileExists : function(user, size, exists){
		exists = exists==null? true : exists;
		
log('getByFileExists : START');
log('getByFileExists : user = ' + user);
		var all = [];
		var photoAll = Tombloo.Photo.findByUser(user);
var c = counter();
log('getByFileExists : photoAll.length = ' + photoAll.length);
// 		return deferredForEach(Tombloo.Photo.findByUser(user).split(100), function(photos){
		return deferredForEach(photoAll.split(100), function(photos){
log('getByFileExists : ' + (c() * 100));
			forEach(photos, function(photo){
				if(photo.checkFile(size) == exists)
					all.push(photo);
			})
			return wait(0);
		}).addCallback(function(){return all});
	},
}
